from flask import (
    Blueprint,
    render_template,
    request,
    session,
    redirect,
    url_for,
    g,
    jsonify
)
from .forms import (
    LoginForm, ResetPwdForm,
    BlockadeForm, UnblockForm,
    TradeForm, UpdateAccountForm
)
from .models import *
from apps.cms.decorators import login_need
import config
from exit import db
from apps.api.models import User, UserRecord
from flask_paginate import Pagination, get_page_parameter
from utils import restful, common_util, img_path, api_util
from apps.common.models import *
from datetime import datetime, date
import os
import shortuuid
from sqlalchemy import or_, func
from decimal import Decimal
from .views_cms import bp
from apps.mall.models import *
from apps.mall.models import Goods, BuyOrder
import requests
import json


@bp.route('/cms2_test/')
def cms2_test():
    return restful.success()


@bp.route('/user_manage/')  # 用户管理
@login_need
def user_manage():
    user_id = request.args.get('user_id')
    parent_id = request.args.get('parent_id')
    submenus_id = request.args.get('submenus_id')
    return render_template('cms/user_manage.html', user_id=user_id, parent_id=parent_id, submenus_id=submenus_id)


@bp.route('/real_user_manage/')  # 用户管理
@login_need
def real_user_manage():
    user_id = request.args.get('user_id')
    status = request.args.get('status')
    status = int(status)
    # parent_id = request.args.get('parent_id')
    # submenus_id = request.args.get('submenus_id')
    print(status)
    if status == 1:
        return render_template('cms/real_user.html', user_id=user_id)
    else:
        return render_template('cms/real_user2.html', user_id=user_id)


@bp.route('/user_manage_info/')     # 用户信息
@login_need
def user_info():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    limit = request.args.get('limit', type=int, default=10)
    start = (page - 1) * int(limit)
    end = start + int(limit)
    users = []
    total = 0
    user_id = request.args.get('user_id')
    parent_id = request.args.get('parent_id')
    submenus_id = request.args.get('submenus_id')
    status = request.args.get('status')
    if parent_id:
        user = User.query.filter_by(id=parent_id).first()
        if user:
            user_obj = User.query.filter_by(p_id=user.id).order_by(
                User.create_time.desc())
            users = user_obj.slice(start, end)
            total = user_obj.count()
    elif submenus_id:
        user = User.query.filter_by(id=submenus_id).first()
        if user.p_path is not None:
            p_path_list = user.p_path.split(',')
            for i in p_path_list:
                user_obj = User.query.filter_by(id=i).first()
                users.append(user_obj)
            users = users[start:end]
            total = len(p_path_list)
    elif status:
        user_obj = User.query.filter(
            or_(User.phone.like("%" + str(user_id) + "%"), User.username.like("%" + str(user_id) + "%")),
            User.status == status
        ).order_by(
            User.create_time.desc())
        users = user_obj.slice(start, end)
        total = user_obj.count()
    else:
        # print(user_id)
        user_obj = User.query.filter(
            or_(User.phone.like("%" + str(user_id) + "%"), User.username.like("%" + str(user_id) + "%"))
        ).order_by(
            User.create_time.desc())
        users = user_obj.slice(start, end)
        total = user_obj.count()
    user_list = list()
    for i in users:

        user_json = i.info_json()
        user_json['user_id'] = i.id
        user_json['blockade'] = i.blockade
        user_json['user_token'] = i.token if i.blockade == 1 else '无'
        user_json['n_level'] = i.n_level
        user_json['user_status'] = '是' if i.status == 1 else '否'
        user_json['n_level_manual'] = i.n_level_manual
        user_json['buy_num'] = i.buy_num
        user_json['user_buy'] = i.user_buy
        user_json['team_buy'] = i.team_buy
        user_json['team_num'] = i.team_num
        user_json['create_time'] = i.create_time.strftime('%Y-%m-%d %H:%M:%S'),
        user_json['direct_num'] = i.direct_num
        user_json['pay_pwd'] = i.pay_pwd
        user_json['real_status'] = '未实名'
        if i.status == 1:
            user_json['real_status'] = '待审核'
        elif i.status == 2:
            user_json['real_status'] = '已实名'
        user_list.append(user_json)
    return restful.table_success(data=user_list, count=total)


@bp.route('/user_blockade/', methods=['POST'])  # 封号
@login_need
def user_blockade():
    form = BlockadeForm(request.form)
    if form.validate():
        user_id = form.id.data
        token = form.token.data
        user = User.query.filter_by(id=user_id).first()
        if not user:
            return restful.params_error(message='找不到这个用户')
        user.blockade = 1
        user.token = token
        record = '后台封号 原因<{}>'.format(token)
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, user_id=user.id, ip=request.remote_addr)
        db.session.add(cms_record)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/reset_user_pwd/', methods=['POST'])  # 修改用户手机号  密码  支付密码
@login_need
def reset_user_pwd():
    pwd = request.form.get('pwd')
    phone = request.form.get('phone')
    pay_pwd = request.form.get('pay_pwd')
    user_id = request.form.get('id')
    # print(phone)
    user = User.query.filter_by(id=user_id).first()
    repeat_user = User.query.filter_by(phone=phone).first()
    if len(phone) != 11:
        return restful.params_error(message='手机号不规范')
    if user is None:
        return restful.params_error(message='未找到用户')
    if repeat_user and user.phone != phone:
        return restful.params_error(message='手机号已被注册')

    if phone != '' and phone is not None:
        if user.phone != phone:
            record = '用户手机号<{}>修改为<{}>'.format(user.phone, phone)
            cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
            db.session.add(cms_record)
            user.phone = phone

    if pay_pwd != '' and pay_pwd is not None:
        if user.pay_pwd != pay_pwd:
            record = '修改用户支付密码'.format(user.pay_pwd, pay_pwd)
            cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
            db.session.add(cms_record)
            user.pay_pwd = pay_pwd
    if pwd is not None and pwd != '':
        user.password = pwd
        user.token = shortuuid.uuid()
        user.error_num = 5
        record = '修改用户登录密码'
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, user_id=user.id, ip=request.remote_addr)
        db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/user_unblock/', methods=['POST'])  # 解封
@login_need
def user_unblock():
    form = UnblockForm(request.form)
    if form.validate():
        user_id = form.id.data
        user = User.query.filter_by(id=user_id).first()
        if not user:
            return restful.params_error(message='找不到这个用户')
        if user.blockade != 1:
            return restful.params_error(message='该账号不是封号状态')
        user.blockade = 0
        user.error_num = 5
        record = "解封账号 封号原因<{}>".format(user.token)
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, user_id=user.id, ip=request.remote_addr)
        db.session.add(cms_record)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/set_user_level/', methods=['POST'])  # 修改用户级别
@login_need
def cms_set_level():
    user_id = request.form.get('user_id')
    user_level = request.form.get('user_level')
    user = User.query.filter_by(id=user_id).first()
    if not user:
        return restful.params_error(message='没有这个用户')
    try:
        user_level = int(user_level)
    except:
        return restful.params_error(message='等级不合法')
    # if user_level not in [0, 1, 2, 3, 4, 5]:
    #     return restful.params_error(message='等级不合法')

    # record = '修改用户等级：原来等级【{}】  现在等级【{}】'.format(user.n_level_manual, user_level)
    if user_level == 1:
        record = '开启用户服务中心'
    else:
        record = '关闭用户服务中心'

    cms_record = CMSRecord(cms_id=g.cms_user.id, user_id=user.id, record=record, ip=request.remote_addr)
    db.session.add(cms_record)
    user.team_leader = user_level
    db.session.commit()
    return restful.success()


@bp.route('/set_user_level_agent/', methods=['POST'])  # 修改用户级别
@login_need
def set_user_level_agent():
    user_id = request.form.get('user_id')
    user_level_agent = request.form.get('user_level_agent', type=int)
    user = User.query.filter_by(id=user_id).first()
    if not user:
        return restful.params_error(message='没有这个用户')
    user_level_agent_str = api_util.level_str(user_level_agent)
    user_level_str = api_util.level_str(user.n_level_agent)

    record = '修改用户代理等级：原来代理等级【{}】  现在代理等级【{}】'.format(user_level_str, user_level_agent_str)

    cms_record = CMSRecord(cms_id=g.cms_user.id, user_id=user.id, record=record, ip=request.remote_addr)
    db.session.add(cms_record)
    user.n_level_agent = user_level_agent
    db.session.commit()
    return restful.success()


@bp.route('/user_record/')  # 用户记录
@login_need
def user_record():
    user_id = request.args.get('user_id')
    return render_template('cms/cms_income_record.html', user_id=user_id)


@bp.route('/user_record_info/')
@login_need
def user_record_info():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    user_id = request.args.get('user_id')
    r_label = request.args.get('r_label')
    record_list = []
    r_label = int(r_label)
    if r_label == 0:
        if user_id:
            record_obj = db.session.query(UserRecord).join(User, UserRecord.user_id == User.id).filter(
                User.phone == user_id, UserRecord.status == 0
            ).order_by(
                UserRecord.id.desc())
        else:
            record_obj = UserRecord.query.filter_by(status=0).order_by(
                UserRecord.id.desc())
    else:
        if user_id:
            record_obj = db.session.query(UserRecord).join(User, UserRecord.user_id == User.id).filter(
                User.phone == user_id, UserRecord.status == 0, UserRecord.r_label == r_label
            ).order_by(
                UserRecord.id.desc())
        else:
            record_obj = UserRecord.query.filter_by(status=0, r_label=r_label).order_by(
                UserRecord.id.desc())
    coin_record = record_obj.slice(start, end)
    for i in coin_record:
        record_json = i.record_json()
        user = User.query.filter_by(id=i.user_id).first()
        record_json['user_id'] = user.id
        record_json['username'] = user.username
        record_json['nickname'] = user.username
        record_json['phone'] = user.phone
        if i.other_id is None:
            record_json['other_phone'] = '无'
        else:
            other = User.query.filter_by(id=i.other_id).first()
            if other:
                record_json['other_phone'] = other.phone
            else:
                record_json['other_phone'] = '无'
        record_json['r_type'] = api_util.record_type(i.r_label, i.r_type)
        record_json['r_label'] = api_util.record_label(i.r_label)

        if i.r_state == 2:
            record_json['num'] = '-{}'.format(i.num)
        else:
            record_json['num'] = '+{}'.format(i.num)

        record_list.append(record_json)
    total = record_obj.count()
    return restful.table_success(data=record_list, count=total)


@bp.route('/update_user_income/', methods=['POST'])  # 更新收益
@login_need
def update_user_income():
    user_id = request.form.get('id')
    income = request.form.get('income')
    integral = request.form.get('integral')
    # ds = request.form.get('ds')
    # hm = request.form.get('hm')
    # jq = request.form.get('jq')
    # income_r = request.form.get('income_r')
    # buy_num = request.form.get('buy_num')
    # ds_buy = request.form.get('ds_buy')

    user = User.query.filter_by(id=user_id).first()
    if user is None:
        return restful.params_error(message='未找到用户')

    # 参数转换
    income = Decimal(income)
    # integral = Decimal(integral)
    # ds = Decimal(ds)
    # hm = Decimal(hm)
    # jq = Decimal(jq)
    # ds_buy = Decimal(ds_buy)
    # buy_num = int(buy_num)
    # income_r = Decimal(income_r)

    # 钱包
    if income:
        record = '用户钱包余额 <{}>---->加 <{}>'.format(user.income, income)
        user.income += income
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
        db.session.add(cms_record)
        api_util.user_record(
            user_id=user.id, r_label=6, r_type=1, r_state=1,
            num=income, r_wallet=1
        )
    #
    # if user.integral != integral:
    #     record = '用户钱包积分 <{}>----->修改为 <{}>'.format(user.integral, integral)
    #     user.integral = integral
    #     cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
    #     db.session.add(cms_record)

    # if user.ds != ds:
    #     record = '用户钱包DS <{}>----->修改为 <{}>'.format(user.ds, ds)
    #     user.ds = ds
    #     cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
    #     db.session.add(cms_record)

    db.session.commit()
    return restful.success()


@bp.route('/update_user_account/', methods=['POST'])  # 修改收款信息
@login_need
def update_user_account():
    user_id = request.form.get('user_id')
    username = request.form.get('username')
    real_name = request.form.get('real_name')
    # ali_pay = request.form.get('ali_pay')
    ali_pay_card = request.form.get('ali_pay_card')
    bank_card = request.form.get('bank_card')
    bank_name = request.form.get('bank_name')
    # usdt_address = request.form.get('usdt_address')
    # usdt_img = request.form.get('usdt_img')

    user = User.query.filter_by(id=user_id).first()

    # 修改用户名
    if user.username != username and username != '' and username != '无':
        record = '用户 用户名 {}----->修改为 {}'.format(user.username, username)
        user.username = username
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
        db.session.add(cms_record)

    # 修改真实姓名
    if user.real_name != real_name and real_name != '' and real_name != '无':
        record = '用户 真实姓名 {}----->修改为 {}'.format(user.real_name, real_name)
        user.real_name = real_name
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
        db.session.add(cms_record)

    # 修改支付宝账号
    if user.ali_pay_card != ali_pay_card and ali_pay_card != '' and ali_pay_card != '无':
        record = '用户 支付宝账号 {}----->修改为 {}'.format(user.ali_pay_card, ali_pay_card)
        user.ali_pay_card = ali_pay_card
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
        db.session.add(cms_record)

    # 银行卡号
    if user.bank_card != bank_card and bank_card != '' and bank_card != '无':
        record = '用户 银行卡号 {}----->修改为 {}'.format(user.bank_card, bank_card)
        user.bank_card = bank_card
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
        db.session.add(cms_record)

    # 修改开户银行
    if user.bank_name != bank_name and bank_name != '' and bank_name != '无':
        record = '用户 开户银行 {}----->修改为 {}'.format(user.bank_name, bank_name)
        user.bank_name = bank_name
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
        db.session.add(cms_record)

    db.session.commit()
    return restful.success()


@bp.route('/user_day_count/')  # 每日统计
@login_need
def user_day_count():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    user_id = request.args.get('user_id')
    today = request.args.get('today')
    if today is None or today == '':
        today = date.today()
    # print(today)
    sql = ""
    user_count = db.session.execute(sql).fetchall()
    total = len(user_count)
    user_count = user_count[start:end]

    pagination = Pagination(bs_version=3, page=page, total=total)
    return render_template('cms/cms_count_day.html', pagination=pagination, user_count=user_count)


@bp.route('/cms_records/')  # 后台操作记录
@login_need
def cms_records():
    user_id = request.args.get('user_id')
    cms_record_list = list()
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    user = User.query.filter(
        or_(User.phone == user_id, User.username.like('%' + str(user_id) + '%'))
    ).first()
    if user:
        cms_record_obj = CMSRecord.query.filter_by(user_id=user.id).order_by(CMSRecord.create_time.desc())
    else:
        cms_record_obj = CMSRecord.query.order_by(CMSRecord.create_time.desc())

    cms_record = cms_record_obj.slice(start, end)
    for i in cms_record:
        record_json = i.cms_record_json()
        admin = CMSUser.query.get(i.cms_id)
        record_json['admin_phone'] = admin.telephone
        user = User.query.filter_by(id=i.user_id).first()
        record_json['user_phone'] = '无'
        record_json['username'] = '无'
        if user:
            record_json['user_phone'] = user.phone
            record_json['username'] = user.username
        if i.record is None:
            record_json['record'] = common_util.cms_record_status(i.r_label, i.r_state)
        else:
            record_json['record'] = i.record
        cms_record_list.append(record_json)
    total = cms_record_obj.count()
    pagination = Pagination(bs_version=3, page=page, total=total)
    return render_template('cms/cms_record.html', pagination=pagination, cms_record_list=cms_record_list, user_id=user_id)


@bp.route('/cms_record_info/')  # 后台操作记录
@login_need
def cms_record_info():
    user_id = request.args.get('user_id')
    cms_record_list = list()
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    filters = list()
    if user_id:
        filters.append(or_(User.phone == user_id, User.username.like('%' + user_id + '%')))
    if 'Z' in g.cms_user.power:
        filters.append(CMSRecord.cms_id == g.cms_user.id)

    cms_record_obj = db.session.query(CMSRecord).join(User, CMSRecord.user_id == User.id).filter(*filters).order_by(CMSRecord.create_time.desc())

    cms_record = cms_record_obj.slice(start, end)
    for i in cms_record:
        record_json = i.cms_record_json()
        admin = CMSUser.query.get(i.cms_id)
        record_json['admin_phone'] = admin.telephone
        user = User.query.filter_by(id=i.user_id).first()
        record_json['user_phone'] = '无'
        record_json['username'] = '无'
        if user:
            record_json['user_phone'] = user.phone
            record_json['username'] = user.username
        if i.record is None:
            record_json['record'] = common_util.cms_record_status(i.r_label, i.r_state)
        else:
            record_json['record'] = i.record
        cms_record_list.append(record_json)
    total = cms_record_obj.count()
    return restful.table_success(data=cms_record_list, count=total)


@bp.route('/real_user_audit/', methods=['POST'])
@login_need
def real_user_audit():
    user_list = request.get_data()
    user_list = json.loads(user_list)

    for i in user_list:
        user = User.query.filter_by(id=i['id'], status=1).first()
        if user is None:
            continue
        # now = datetime.now()

        user.status = 2

        record = '完成注册实名审核'
        # 后台记录
        cms_record = CMSRecord(
            cms_id=g.cms_user.id,
            ip=request.remote_addr,
            record=record,
            user_id=user.id,
        )
        db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/fail_user_audit/', methods=['POST'])    # 失败用户审核
@login_need
def fail_user_audit():
    user_list = request.get_data()
    user_list = json.loads(user_list)
    # print(user_list)

    for i in user_list:
        user = User.query.filter_by(id=i['id'], status=1).first()
        if user is None:
            continue
        # now = datetime.now()

        user.status = 0
        user.sex = None
        user.id_card = None
        user.id_img = None

        record = '失败实名审核'
        # 后台记录
        cms_record = CMSRecord(
            cms_id=g.cms_user.id,
            ip=request.remote_addr,
            record=record,
            user_id=user.id,
        )
        db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/reset_user_real/', methods=['POST'])     # 重置用户实名
@login_need
def reset_user_real():
    user_id = request.form.get('user_id')
    user = User.query.filter_by(id=user_id).first()
    if user is None:
        return restful.params_error(message='未找到用户')
    user.status = 0
    user.sex = None
    user.id_card = None
    user.id_img = None

    record = '重置用户实名'
    # 后台记录
    cms_record = CMSRecord(
        cms_id=g.cms_user.id,
        ip=request.remote_addr,
        record=record,
        user_id=user.id,
    )
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/user_open_status/', methods=['POST'])   # 开通用户点对点
@login_need
def user_open_status():
    user_id = request.form.get('user_id')
    status = request.form.get('status')
    user = User.query.filter_by(id=user_id).first()
    if user is None:
        return restful.params_error(message='未找到用户')
    status = int(status)
    print(status)
    if status == 0:
        record = '用户关闭点对点'
    else:
        record = '用户开启点对点'

    user.open_status = status
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
    db.session.add(cms_record)
    db.session.commit()
    return restful.success()


@bp.route('/transfer_manage/')      # 转让管理
@login_need
def transfer_manage():
    return render_template('cms/user_transfer.html')


@bp.route('/transfer_deal/', methods=['POST'])      # 协议转让
@login_need
def transfer_deal():
    try:
        sell_id = request.form.get('sell_id')
        buy_id = request.form.get('buy_id')
        num = request.form.get('num')

        seller = User.query.filter_by(phone=sell_id).first()
        buyer = User.query.filter_by(phone=buy_id).first()

        if seller is None:
            return restful.params_error(message='未找到转让账号')
        if buyer is None:
            return restful.params_error(message='未找到被转让账号')

        buy_deal = BuyDeal.query.filter(
            BuyDeal.buyer_id == seller.id,
            BuyDeal.s_num >= num,
            BuyDeal.t_type == 1,
        ).with_for_update().first()
        if buy_deal is None:
            return restful.params_error(message='未找到可转让的批次')

        num = int(num)
        buy_deal.s_num -= num
        if buy_deal.s_num < buy_deal.s_num_sell:
            buy_deal.s_num_sell = buy_deal.s_num

        create_deal = BuyDeal(
            buyer_id=buyer.id, seller_id=seller.id,
            sell_batch_id=buy_deal.id, deal_num=num, deal_price=buy_deal.deal_price,
            deal_type=3, deal_money=buy_deal.deal_price * num, s_num=num, s_num_sell=0, tn_day=0,
            goods_id=buy_deal.goods_id, buy_fee=0, sell_fee=0, t_type=1
        )
        db.session.add(create_deal)
        if seller.phone == '15224897513':
            # 卖家记录
            api_util.user_record(
                user_id=seller.id, r_label=10, r_type=5, r_state=2, num=num, r_wallet=1, status=0,
                other_id=buyer.id, r_coin=800, order_id=buy_deal.id)

            # 买家记录
            api_util.user_record(user_id=buyer.id, r_label=10, r_type=4, r_state=1, num=num, r_wallet=1, status=0, other_id=None, r_coin=800, order_id=buy_deal.id)

        else:
            api_util.user_record(
                user_id=seller.id, r_label=10, r_type=5, r_state=2, num=num, r_wallet=1, status=0,
                other_id=None, r_coin=800, order_id=buy_deal.id)

            api_util.user_record(user_id=buyer.id, r_label=10, r_type=6, r_state=1, num=num, r_wallet=1, status=0,
                                 other_id=seller.id, r_coin=800, order_id=buy_deal.id)

        record = '转出冻结票：<{}>个 到 <{}>'.format(num, buyer.phone)
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=seller.id)
        db.session.add(cms_record)

        db.session.commit()
        return restful.success()
    except Exception as e:
        print(e)
        db.session.close()
        return restful.params_error(message='网络错误 请重试!')


@bp.route('/user_income_transfer/', methods=['POST'])
@login_need
def user_income_transfer():
    src_phone = request.form.get('user_phone')
    dst_phone = request.form.get('other_phone')

    if src_phone == dst_phone:
        return restful.params_error(message='手机号不能一样')
    src_user = db.session.query(User).filter_by(phone=src_phone).first()
    if not src_user:
        return restful.params_error(message='未找到src用户')
    dst_user = db.session.query(User).filter_by(phone=dst_phone).first()
    if not dst_user:
        return restful.params_error(message='未找到dst用户')

    # 转移资产
    if src_user.income > 0:
        dst_user.income += src_user.income
        api_util.user_record(
            user_id=src_user.id, r_label=11, r_type=3, r_state=2,
            num=src_user.income, other_id=dst_user.id, r_wallet=1
        )
        api_util.user_record(
            user_id=dst_user.id, r_label=11, r_type=4, r_state=1,
            num=src_user.income, other_id=src_user.id, r_wallet=1
        )
        src_user.income = 0

    if src_user.income_dj > 0:
        dst_user.income_dj += src_user.income_dj
        api_util.user_record(
            user_id=src_user.id, r_label=11, r_type=5, r_state=2,
            num=src_user.income_dj, other_id=dst_user.id, r_wallet=1
        )
        api_util.user_record(
            user_id=dst_user.id, r_label=11, r_type=6, r_state=1,
            num=src_user.income_dj, other_id=src_user.id, r_wallet=1
        )
        src_user.income_dj = 0

    if src_user.income_r > 0:
        dst_user.income_r += src_user.income_r
        api_util.user_record(
            user_id=src_user.id, r_label=11, r_type=7, r_state=2,
            num=src_user.income_r, other_id=dst_user.id, r_wallet=1
        )
        api_util.user_record(
            user_id=dst_user.id, r_label=11, r_type=8, r_state=1,
            num=src_user.income_r, other_id=src_user.id, r_wallet=1
        )
        src_user.income_r = 0

    # 转移批次
    src_deal = db.session.query(BuyDeal).filter(BuyDeal.buyer_id == src_user.id, BuyDeal.s_num > 0).all()
    for i in src_deal:
        # 新建一条
        api_util.deal_record(dst_user.id, src_user.id, i.deal_price, i.deal_num, i.s_num, i.s_num_sell, i.t_type,
                                3, i.tn_day, i.goods_id, i.id, i.status)

        # 做记录
        api_util.user_record(
            user_id=src_user.id, r_label=10, r_type=5, r_state=2,
            num=i.s_num, r_coin=i.deal_price, other_id=dst_user.id,
            order_id=i.id, r_wallet=1
        )
        api_util.user_record(
            user_id=dst_user.id, r_label=10, r_type=6, r_state=1,
            num=i.s_num, r_coin=i.deal_price, other_id=src_user.id,
            order_id=i.id, r_wallet=1
        )

        # 原有清0
        i.s_num = 0
        i.s_num_sell = 0

    db.session.commit()
    return restful.success()


@bp.route('/user_freed/')  # 后台释放订单
@login_need
def user_buy_deal():
    user_id = request.args.get('user_id')
    # print(user_id)
    return render_template(
        'cms/user_freed.html', user_id=user_id
    )


@bp.route('/user_freed_info/')  # buy_deal信息
@login_need
def user_freed_info():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * 10
    end = start + 10
    order_list = list()
    user_id = request.args.get('user_id')
    print(user_id)

    order_obj = BuyDeal.query.filter(
        BuyDeal.buyer_id == user_id,
        BuyDeal.deal_type == 3,
        BuyDeal.status == 1,
        BuyDeal.s_num_sell > 0,
        # BuyDeal.seller_id == '1',
        BuyDeal.t_type == 0
    )

    total = order_obj.count()
    orders = order_obj.slice(start, end)
    for i in orders:
        order_json = i.buy_deal_json()
        user = User.query.filter_by(id=i.buyer_id).first()
        order_json['username'] = user.username
        order_json['nickname'] = user.nickname
        order_json['real_name'] = user.real_name
        order_json['user_id'] = user.id
        order_json['phone'] = user.phone

        order_list.append(order_json)
    return restful.table_success(data=order_list, count=total)


@bp.route('/freed_buy_deal/', methods=['POST'])
@login_need
def freed_buy_deal():
    bath_id = request.form.get('bath_id')
    num = request.form.get('num')
    num = int(num)
    buy_deal = BuyDeal.query.filter_by(id=bath_id).with_for_update().first()
    if buy_deal is None:
        return restful.params_error(message='未找到数据')
    if num < 0:
        return restful.params_error(message='不能小于0')

    if buy_deal.s_num_sell < num:
        return restful.params_error(message='可释放数量不足')

    buy_deal.s_num_sell -= num
    buy_deal.s_num -= num

    create_buy_deal = BuyDeal(
        buyer_id=buy_deal.buyer_id, seller_id=buy_deal.buyer_id,
        sell_batch_id=buy_deal.id, deal_price=buy_deal.deal_price,
        deal_money=buy_deal.deal_price * num, deal_num=num, goods_id=buy_deal.goods_id,
        deal_type=3, s_num=num, s_num_sell=num, t_type=0, status=0, tn_day=0, buy_fee=0, sell_fee=0
    )
    db.session.add(create_buy_deal)
    # 做记录
    api_util.user_record(
        user_id=buy_deal.buyer_id, r_label=10, r_type=20, r_state=1,
        num=num, r_coin=buy_deal.deal_price,
        order_id=buy_deal.id, r_wallet=1
    )

    record = '释放<{}>锁定票'.format(num)
    cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=buy_deal.buyer_id)
    db.session.add(cms_record)

    db.session.commit()
    return restful.success()


@bp.route('/freed_transfer/', methods=['POST'])      # 待释放转锁定
@login_need
def freed_transfer():
    try:
        user_phone = request.form.get('user_phone')
        num = request.form.get('num')

        user = User.query.filter_by(phone=user_phone).first()

        if user is None:
            return restful.params_error(message='未找到账号')
        num = int(num)
        if num < 0:
            return restful.params_error(message='不能小于0')

        buy_deal = BuyDeal.query.filter(
            BuyDeal.buyer_id == user.id,
            BuyDeal.s_num >= num,
            BuyDeal.t_type == 2,
        ).with_for_update().first()
        if buy_deal is None:
            return restful.params_error(message='未找到可转让的批次')

        buy_deal.s_num -= num
        if buy_deal.s_num < buy_deal.s_num_sell:
            buy_deal.s_num_sell = buy_deal.s_num

        create_deal = BuyDeal(
            buyer_id=user.id, seller_id=user.id,
            sell_batch_id=buy_deal.id, deal_num=num, deal_price=buy_deal.deal_price,
            deal_type=3, deal_money=buy_deal.deal_price * num, s_num=num, s_num_sell=num, tn_day=buy_deal.tn_day,
            goods_id=buy_deal.goods_id, buy_fee=0, sell_fee=0, t_type=0, status=1
        )
        db.session.add(create_deal)
        # 卖家记录
        api_util.user_record(
            user_id=user.id, r_label=10, r_type=19, r_state=1, num=num, r_wallet=1, status=0, r_coin=800, order_id=buy_deal.id)

        record = '待释放转锁定<{}>'.format(num)
        cms_record = CMSRecord(cms_id=g.cms_user.id, record=record, ip=request.remote_addr, user_id=user.id)
        db.session.add(cms_record)

        db.session.commit()
        return restful.success()
    except Exception as e:
        print(e)
        db.session.close()
        return restful.params_error(message='网络错误 请重试!')


